<template>
  <q-dialog v-model="innerDialogShow" position="bottom">
    <q-card bordered style="width:600px; max-width: 600px">
      <q-card-section class="q-pa-none">
        <q-carousel
            swipeable
            animated
            navigation
            infinite
            v-model="backgroundId"
            style="height: 300px;"
        >
          <q-carousel-slide v-for="image in backgrounds" class="q-pa-none"
                            :img-src="image.url"
                            :name="image.id" :key="image.id">
            <q-img v-if="image.url" :src="image.url" alt="" class="full-height"/>
            <div v-if="image.color" class="full-height full-width"
                 :style="{backgroundColor: image.color}"/>
          </q-carousel-slide>
          <template v-slot:navigation-icon="{ active, onClick, index }">
            <q-img v-if="backgrounds[index].url"
                   :src="backgrounds[index].url"
                   class="background-thumbnail"
                   :class="{'background-thumbnail--active': active}"
                   @click="onClick"/>
            <div v-if="backgrounds[index].color"
                 class="background-thumbnail"
                 :class="{'background-thumbnail--active': active}"
                 :style="{backgroundColor: backgrounds[index].color}"
                 @click="onClick"/>
          </template>
          <template v-slot:control>
            <q-carousel-control
                position="top-left"
                :offset="[18, 18]"
                class="text-white rounded-borders"
                style="background: rgba(0, 0, 0, .3); padding: 4px 8px;"
            >
              <q-btn @click.stop="removeImage"
                     flat round dense color="white" icon="delete_forever"/>
            </q-carousel-control>
            <q-carousel-control
                position="top-right"
                :offset="[18, 18]"
                class="text-white rounded-borders"
                style="background: rgba(0, 0, 0, .3); padding: 4px 8px;"
            >
              <q-toggle dense dark color="orange" v-model="autoPlay" label="自动切换"/>
              <q-btn @click.stop="$emit('input',false)"
                     flat round dense color="white" icon="expand_more"/>
            </q-carousel-control>
          </template>
        </q-carousel>
        <div class="row">
          <q-field class="col" filled label="新增纯色背景" @click="createColorBackground">
            <template v-slot:prepend>
              <q-icon name="colorize"/>
            </template>
          </q-field>
          <q-file class="col" filled v-model="file" label="上传图片背景" @input="uploadBackground">
            <template v-slot:prepend>
              <q-icon name="cloud_upload"/>
            </template>
          </q-file>
        </div>
      </q-card-section>
    </q-card>
    <q-dialog v-model="showColorPick">
      <q-card style="width: 350px">
        <q-color
            v-model="backgroundColor"
            no-header
            no-footer
            default-view="palette"
            class="my-picker"
        />
        <q-separator vertical/>
        <div v-if="lastColor!==''"><span>此前颜色</span><span>{{ lastColor }}</span></div>
      </q-card>
    </q-dialog>
  </q-dialog>
</template>

<script>
import axios from 'axios'
import iCommon from 'src/api/common'
import { genId } from 'src/utils/clent-tool'
import dialog from 'src/mixins/form'
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'TheBackgroundManagement',
  mixins: [dialog],
  data () {
    const options = this.$store.state.workbench.options
    return {
      panelShow: this.show,
      backgroundId: options.backgroundId,
      backgroundColor: '',
      autoPlay: options.autoPlay,
      file: null,
      uploadUrl: iCommon.$additionalOptions.baseURL + iCommon.uploadBackground.$options.url,
      lastColor: '',
      showColorPick: false
    }
  },
  computed: {
    backgrounds () {
      return this.$store.state.workbench.options.backgrounds
    },
    color () {
      return this.$store.state.workbench.options.color
    }
  },
  watch: {
    backgroundId () {
      this.$store.dispatch('workbench/updateOptions', {
        backgroundId: this.backgroundId
      })
    },
    async backgroundColor () {
      const currentBackgrounds = this.$store.state.workbench.options.backgrounds
      const newBackgroundId = genId('BK')
      await this.$store.dispatch('workbench/updateOptions', {
        backgrounds: [
          ...currentBackgrounds,
          {
            id: newBackgroundId,
            color: this.backgroundColor
          }
        ],
        backgroundId: newBackgroundId
      })
      this.showColorPick = false
    },
    autoPlay () {
      this.$store.dispatch('workbench/updateOptions', {
        autoPlay: this.autoPlay
      })
    },
    '$store.state.workbench.options' (options) {
      this.autoPlay = options.autoPlay
      this.backgroundId = options.backgroundId
    }
  },
  mounted () {
    // ...
  },
  methods: {
    async uploadBackground () {
      const formData = new FormData()
      formData.append('file', this.file)
      const res = await axios.post(this.uploadUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        withCredentials: true
      })
      if (res.data && res.data.data) {
        const imageUrl = res.data.data
        const currentBackgrounds = this.$store.state.workbench.options.backgrounds
        await this.$store.dispatch('workbench/updateOptions', {
          backgrounds: [
            ...currentBackgrounds,
            {
              id: genId('BK'),
              url: imageUrl
            }
          ]
        })
      }
    },
    createColorBackground () {
      this.showColorPick = true
    },
    removeImage () {
      const currentImages = this.$store.state.workbench.options.backgrounds
      if (currentImages.length <= 0) {
        return this.$q.notify({
          icon: 'announcement',
          message: '背景已设置为空白 ☹',
          color: 'red',
          position: 'top',
          timeout: 1500
        })
      }
      this.$q.dialog({
        title: '警告',
        message: '是否确定要删除壁纸？（不能撤销）',
        cancel: true,
        persistent: true
      }).onOk(async () => {
        let currentIndex = 0
        const filterImages = currentImages.filter((e, index) => {
          currentIndex = index
          return e.id !== this.backgroundId
        })
        const newBackgroundImageId = (filterImages[currentIndex - 1] || filterImages[0]).id
        await this.$store.dispatch('workbench/updateOptions', {
          backgrounds: filterImages,
          backgroundId: newBackgroundImageId
        })
      })
    }
  }
})
</script>

<style lang="scss" scoped>
.background-thumbnail {
  margin: 2px;
  height: 50px;
  width: 80px;
  display: inline-block;
  cursor: pointer;
  border: 1px solid transparent;
  border-radius: 4px;
  vertical-align: middle;
  opacity: 1;
  transition: border 0.3s;

  &--active {
    border-color: white;
    cursor: default;
  }
}
</style>
